<?php
/**
 * @Author: lianlianzan(13040@qq.com)
 * @Date:   2018-08-18 16:40:16
 * @Last Modified by:   zhaozilong
 * @Last Modified time: 2018-09-02 17:01:19
 */

namespace app\common\logic;

class User extends Base {
	// 设置数据表（不含前缀）
	protected $name = 'user';

	public static function login($username, $password, $rememberme = false, $type = 6){
		$md5Password = sp_password($password);

		//获取用户数据
		$user = model('common/User')->getInfoByUsername($username);
		//print_r($user);exit;

		if (!empty($user)) {
			/* 验证用户密码 */
			if ($md5Password === $user['password']) {
				self::autoLogin($user, $rememberme); //更新用户登录信息
				return ['code'=>1,'msg'=>'登录成功','data'=>['id'=>$user['id']]];
			} else {
				return ['code'=>0,'msg'=>'用户名或密码错误'];
			}
		} else {
			return ['code'=>0,'msg'=>'用户不存在或被禁用'];
		}
	}

	/**
	 * 自动登录
	 * @param  [type]  $user	   用户对象
	 * @param  boolean $rememberme 是否记住登录，默认7天
	 * @return [type]			   [description]
	 */
	public static function autoLogin($user, $rememberme = true){
		if (empty($user)) return false;
		//print_r($user);exit;

		$UserDao = model('common/User');

		//最后登录时间
		$data = array(
			'last_login_time' => time(),
		);
		$UserDao->baseUpdateData($user['id'], $data);

		// 记录登录SESSION和COOKIES
		// $result = self::setUserAuthSession($user);
		// $auth_login = $result['auth_login'];
		// $auth_login_sign = $result['auth_login_sign'];
		// // 更新登录信息
		// $data = [
		// 	'last_login_ip'		   => request()->ip(),
		// 	'last_login_time'	   => $auth_login['last_login_time'],
		// 	'activation_auth_sign' => $auth_login_sign,
		// ];
		//
		// self::where(['uid' => $auth_login['uid']])->update($data);

		// 记住登录
		if ($rememberme) {
			//print_r($user);exit;
			cookie('user_login_auth', _authcode($user['id']."\t".$user['password'], 'ENCODE')); //, config('COOKIE_EXPIRE')
		}
	}

	/**
	 * 判断是否登录
	 * @return int 0或用户id
	 */
	public static function isLogin() {
		$list = explode("\t", addslashes(_authcode(cookie('user_login_auth'))));
		//print_r($list);exit;
		if (count($list) > 1) {
			list($winduid, $windpwd) = $list;
		}

		if ($winduid) {
			return $winduid;
		} else {
			return 0;
		}
	}

	public static function logout() {
		cookie('user_login_auth', null);
	}
	
}